package com.keepers.repair.view.bindview;

import android.view.LayoutInflater;
import android.view.ViewGroup;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;

/**
 * auth aboom by 2018/2/26.
 */

public class BindViewHelper {

    private final List<ViewHolder> mCachesList = new ArrayList<>();
    private final SoftReference<ViewGroup> mWeakReference;
    private final LayoutInflater           mInflater;

    public BindViewHelper(ViewGroup viewGroup) {
        mWeakReference = new SoftReference<>(viewGroup);
        mInflater = LayoutInflater.from(viewGroup.getContext());
    }

    public <T> void bindUI(int itemId, List<T> data, OnBindData<T> onBindData) {
        ViewGroup viewGroup = mWeakReference.get();
        if (viewGroup == null) {
            return;
        }
        if (data != null && data.size() > 0) {
            if (data.size() < viewGroup.getChildCount()) {//数据源小于现有子View，删除后面多的
                viewGroup.removeViews(data.size(), viewGroup.getChildCount() - data.size());
                //删除View也清缓存
                while (mCachesList.size() > data.size()) {
                    mCachesList.remove(mCachesList.size() - 1);
                }
            }
            for (int i = 0; i < data.size(); i++) {
                ViewHolder holder;
                if (mCachesList.size() - 1 >= i) {//说明有缓存，不用inflate，否则inflate
                    holder = mCachesList.get(i);
                } else {
                    holder = new ViewHolder(mInflater.inflate(itemId, viewGroup, false));
                    mCachesList.add(holder);//inflate 出来后 add进来缓存
                }
                if (onBindData != null) {
                    onBindData.onBind(i, data.size(), data.get(i), holder);
                }
                //如果View没有父控件 添加
                if (holder.getConvertView().getParent() == null) {
                    viewGroup.addView(holder.getConvertView());
                    if (onBindData != null) {
                        onBindData.onViewSize(i, data.size(), holder);
                    }
                }
            }
        } else {
            viewGroup.removeAllViews();
        }
    }
}
